<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>摄像头拍照</title>
</head>
<body style="text-align:center">
<input  th:text="${sfzh}" th:value="${sfzh}" id="sfzh" hidden="hidden"/>
	<div>

		<div class="renxiang_left_box">
			<video id="video" width="430" height="325" autoplay></video>
		</div>
		<!-- 采集到照片放入此区域 -->
		<div id="gatherDiv" class="renxiang_center_box2">
			<img id="gather" src="" />
		</div>
		<button id="capture">拍照</button>
		<button onClick="UploadPic();" type="button">保存照片</button>
		<!-- 图形容器 -->
		<div id="canvasDiv" class="renxiang_center_box">
			<canvas id="canvas" width="430" height="325"></canvas>
		</div>
	</div>

	<script src="../js/jquery-3.2.1.min.js"></script>
	<script>
    //访问用户媒体设备的兼容方法
    function getUserMedia(constraints, success, error) {
        if (navigator.mediaDevices.getUserMedia) {
            //最新的标准API
            navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error);
        } else if (navigator.webkitGetUserMedia) {
            //webkit核心浏览器
            navigator.webkitGetUserMedia(constraints,success, error)
        } else if (navigator.mozGetUserMedia) {
            //firfox浏览器
            navigator.mozGetUserMedia(constraints, success, error);
        } else if (navigator.getUserMedia) {
            //旧版API
            navigator.getUserMedia(constraints, success, error);
        }
    };

    let video = document.getElementById('video');
    let canvas = document.getElementById('canvas');
    let context = canvas.getContext('2d');

    //下面的代码是保存canvas标签里的图片并且将其按一定的规则重命名
    //var type = 'png';
    var type = 'jpeg';

    var _fixType = function(type) {
        type = type.toLowerCase().replace(/jpg/i, 'jpeg');
        var r = type.match(/png|jpeg|bmp|gif/)[0];
        return 'image/' + r;
    };
    // 下载后的文件名规则
    var filename = (new Date()).getTime() + '.' + type;

    function success(stream) {
        //兼容webkit核心浏览器
        let CompatibleURL = window.URL || window.webkitURL;
        //将视频流设置为video元素的源
        console.log(stream);

        //video.src = CompatibleURL.createObjectURL(stream);
        video.srcObject = stream;
        video.play();
    };

    function error(error) {
        console.log('访问用户媒体设备失败${error.name}, ${error.message}');
    };

    if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) {
        //调用用户媒体设备, 访问摄像头
        getUserMedia({video : {width: 480, height: 320}}, success, error);
    } else {
        alert('不支持访问用户媒体');
    };

    document.getElementById('capture').addEventListener('click', function () {
        var image = context.drawImage(video, 0, 0, 480, 320);
        //image.src = canvas.toDataURL("image/test111.png");
    });

    //上传图片到后台
    function UploadPic() {
        // Generate the image data（将Canvas的内容保存为图片借助toDataURL来实现） 方法返回一个包含图片展示的 data URI 。
        var Pic = document.getElementById("canvas").toDataURL("image/jpg");
        //对其进行base64编 之后的字符串
        Pic = Pic.replace(/^data:image\/(png|jpg);base64,/,"")
        // Sending the image data to Server
        $.ajax({
            type:'POST',
            url: '/junior/doSavePhoto',
            data: {'imgData': Pic,
            	'sfzh':$("#sfzh").val()},
            //async: false,
    		//设置超时 
    		timeout:10000,
            dataType: 'json',
            success: function(data){
                if(data.success){
                    alert('上传成功');
                }else{
                    alert('上传失败');
                }
            },
            error: function(err){
                //alert('网络故障');
            }
        });
    }
</script>
</body>
</html>